<template>
  <div class="setup-config-container">
    <el-card class="filter-card" shadow="never">
      <el-form :inline="true" :model="searchForm" label-width="80px">
        <el-form-item label="参数名称">
          <el-input v-model="searchForm.configName" placeholder="请输入参数名称" clearable />
        </el-form-item>
        <el-form-item label="参数键名">
          <el-input v-model="searchForm.configKey" placeholder="请输入参数键名" clearable />
        </el-form-item>
        <el-form-item label="参数端">
          <el-select v-model="searchForm.configType" placeholder="请选择" clearable style="width: 180px">
            <el-option label="后台" value="1" />
            <el-option label="代理商端" value="2" />
            <el-option label="用户端" value="3" />
            <el-option label="商家端" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card" shadow="never">
      <div class="table-toolbar">
        <el-button type="primary" @click="openAddDialog">新增参数</el-button>
      </div>

      <el-table :data="tableData" v-loading="loading" border>
        <el-table-column prop="configId" label="ID" width="80" />
        <el-table-column prop="configName" label="参数名称" min-width="150" />
        <el-table-column prop="configKey" label="参数键名" min-width="160" />
        <el-table-column prop="configValue" label="参数键值" min-width="200" show-overflow-tooltip />
        <el-table-column prop="configType" label="参数端" width="120">
          <template #default="{ row }">
            <span>{{ renderConfigType(row.configType) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" min-width="180" />
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button text type="primary" @click="openEditDialog(row)">编辑</el-button>
            <el-popconfirm :title="`确认删除【${row.configName}】吗？`" @confirm="handleDelete(row)">
              <template #reference>
                <el-button text type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <div class="table-pagination">
        <el-pagination
          v-model:current-page="searchForm.page"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑参数' : '新增参数'"
      width="520px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="90px">
        <el-form-item label="参数名称" prop="configName">
          <el-input v-model="formData.configName" placeholder="请输入参数名称" maxlength="100" show-word-limit />
        </el-form-item>
        <el-form-item label="参数键名" prop="configKey">
          <el-input
            v-model="formData.configKey"
            placeholder="请输入参数键名（建议使用全局唯一的英文标识）"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="参数键值" prop="configValue">
          <el-input
            v-model="formData.configValue"
            placeholder="请输入参数键值"
            type="textarea"
            :rows="3"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="参数端" prop="configType">
          <el-select v-model="formData.configType" placeholder="请选择参数端" style="width: 200px">
            <el-option label="后台" value="1" />
            <el-option label="代理商端" value="2" />
            <el-option label="用户端" value="3" />
            <el-option label="商家端" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="formData.remark"
            placeholder="请输入备注"
            type="textarea"
            :rows="2"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { ConfigService } from '@/api/configApi'
import type { ConfigItem, ConfigQuery } from '@/api/model/configModel'
import { ApiStatus } from '@/utils/http/status'

const searchForm = reactive<ConfigQuery>({
  configName: '',
  configKey: '',
  configType: '',
  page: 1,
  pageSize: 10
})

const tableData = ref<ConfigItem[]>([])
const total = ref(0)
const loading = ref(false)

const dialogVisible = ref(false)
const isEdit = ref(false)
const submitLoading = ref(false)
const formRef = ref<FormInstance>()

const formData = reactive<ConfigItem>({
  configId: undefined,
  configName: '',
  configKey: '',
  configValue: '',
  configType: '',
  remark: ''
})

const formRules: FormRules = {
  configName: [{ required: true, message: '请输入参数名称', trigger: 'blur' }],
  configKey: [{ required: true, message: '请输入参数键名', trigger: 'blur' }],
  configValue: [{ required: true, message: '请输入参数键值', trigger: 'blur' }],
  configType: [{ required: true, message: '请选择参数端', trigger: 'change' }]
}

const renderConfigType = (type?: string) => {
  switch (type) {
    case '1':
      return '后台'
    case '2':
      return '代理商端'
    case '3':
      return '用户端'
    case '4':
      return '商家端'
    default:
      return type || '-'
  }
}

const fetchList = async () => {
  loading.value = true
  try {
    const res = await ConfigService.getAll(searchForm)
    if (String(res.code) === String(ApiStatus.success) && res.data) {
      tableData.value = res.data.list || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取参数列表失败')
    }
  } catch (e) {
    console.error(e)
    ElMessage.error('获取参数列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  searchForm.page = 1
  fetchList()
}

const handleReset = () => {
  searchForm.configName = ''
  searchForm.configKey = ''
  searchForm.configType = ''
  searchForm.page = 1
  searchForm.pageSize = 10
  fetchList()
}

const handleSizeChange = (size: number) => {
  searchForm.pageSize = size
  searchForm.page = 1
  fetchList()
}

const handleCurrentChange = (page: number) => {
  searchForm.page = page
  fetchList()
}

const resetForm = () => {
  formRef.value?.resetFields()
  formData.configId = undefined
}

const openAddDialog = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const openEditDialog = (row: ConfigItem) => {
  isEdit.value = true
  resetForm()
  formData.configId = row.configId
  formData.configName = row.configName
  formData.configKey = row.configKey
  formData.configValue = row.configValue
  formData.configType = row.configType
  formData.remark = row.remark
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return
  try {
    const valid = await formRef.value.validate()
    if (!valid) return
    submitLoading.value = true
    const payload: ConfigItem = {
      configId: formData.configId,
      configName: formData.configName,
      configKey: formData.configKey,
      configValue: formData.configValue,
      configType: formData.configType,
      remark: formData.remark
    }
    if (isEdit.value && payload.configId) {
      const res = await ConfigService.update(payload)
      if (String(res.code) === String(ApiStatus.success)) {
        ElMessage.success('修改成功')
      } else {
        ElMessage.error(res.message || '修改失败')
      }
    } else {
      const res = await ConfigService.save(payload)
      if (String(res.code) === String(ApiStatus.success)) {
        ElMessage.success('新增成功')
      } else {
        ElMessage.error(res.message || '新增失败')
      }
    }
    dialogVisible.value = false
    fetchList()
  } catch (e) {
    console.error(e)
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

const handleDelete = async (row: ConfigItem) => {
  if (!row.configId) return
  try {
    const res = await ConfigService.delete(row.configId)
    if (String(res.code) === String(ApiStatus.success)) {
      ElMessage.success('删除成功')
      if (tableData.value.length === 1 && searchForm.page > 1) {
        searchForm.page -= 1
      }
      fetchList()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (e) {
    console.error(e)
    ElMessage.error('删除失败')
  }
}

onMounted(() => {
  fetchList()
})
</script>

<style scoped lang="scss">
.setup-config-container {
  padding: 16px;

  .filter-card {
    margin-bottom: 16px;
  }

  .table-card {
    .table-toolbar {
      display: flex;
      justify-content: space-between;
      margin-bottom: 16px;
    }

    .table-pagination {
      display: flex;
      justify-content: flex-end;
      padding-top: 16px;
    }
  }
}
</style>


